package com.andova.module.app;

import android.app.Activity;

import androidx.collection.ArrayMap;

import com.andova.lifecycle.IDelegate;
import com.andova.lifecycle.ILifecycle;
import com.andova.manager.AndovaModuleManager;
import com.andova.module.api.IModuleDelegate;
import com.andova.module.edit.ModuleActivityAgent;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018-03-20.
 *
 * @author kzaxil
 * @since 1.0.0
 */
public class ModuleLifecycle implements ILifecycle {
    private Map<Activity, ModuleActivityAgent> mAgentMap = new ArrayMap<>(1);

    @Override
    public void onActivityCreated(Activity activity, List<IDelegate> delegates) {
        ModuleActivityAgent agent = mAgentMap.get(activity);
        if (agent == null) {
            agent = new ModuleActivityAgent(activity);
        }
        mAgentMap.put(activity, agent);
    }

    @Override
    public void onActivityStarted(Activity activity, List<IDelegate> delegates) {
        ModuleActivityAgent agent = mAgentMap.get(activity);
        if (agent == null) return;
        for (IDelegate delegate : delegates) {
            if (!(delegate instanceof IModuleDelegate)) return;
            agent.onCreated(((IModuleDelegate) delegate).checkedGridView(), ((IModuleDelegate) delegate).uncheckedGridView());
        }
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        AndovaModuleManager.obj().module().removeCheckedGridViewId(activity);
        AndovaModuleManager.obj().module().removeUncheckedGridViewId(activity);
        mAgentMap.get(activity).broadcastModuleChanged();
        mAgentMap.remove(activity);
    }
}
